<?php
Class Turns extends CI_Model
{
	
	
	public function __construct() {
		parent::__construct();
//		$this->$gameId = $this->session->userdata('gameId');
//		$this->$current_turnId = $this->session->userdata('current_turnId');
//		$tableName = "turns";	
	}
	
//	public function acceptCards($playerId){
//		$activeTurnCards = $this->getActiveTurnCards();
//		$CI =& get_instance();
//        $CI->load->model('talon');
//		foreach ($activeTurnCards as $card) {
//			$talonId = $card->talon_id;
//			$this->disableTurn($talonId);
//			$CI->talon->updateTalonCardByGameId($talonId,array("replenishee_id"=>$playerId));
//		}
//	}
	
	public function endAttack($playerId){
		$activeTurnCards = $this->getActiveTurnCards();
		$CI =& get_instance();
        $CI->load->model('talon');
		foreach ($activeTurnCards as $card) {
			$talonId = $card->talon_id;
			$this->disableTurn($talonId);
			$CI->talon->removeTalonCardFromGame($talonId);
		}
	}
	
	public function getActiveTurnCards(){
		$this->db->where('active',1);
		return $this->db->get('turns')->result();
	}
	
	public function removeData(){
		$this->db->query('delete from turns;');
	}
	
	public function acceptCards($playerId){
		$activeTurnCards = $this->getActiveTurnCards();
		$CI->talon->updateReplenisheeId($activeTurnCards,$playerId);
	}
	
	public function removeTurnCardFromGame($talonId){ 							// should be called from talon model only because it has
		$this->disableTurn($talonId);											// pre-requisite procedures
	}
	private function disableTurn($talonId){
		$updateData = array('active'=>'false');	
		$this->db->where('talon_id',$talonId);
		$this->db->update('turns',$updateData);
	}
	
	private	function updateTurnCardActive($turnId, $active){
		$updateData = array("active"=>$active);
		$this->db->where("id", $turnId);
		$this->db->update('turns', $updateData);
	}
	
	public function insertAttackTurn($playerId, $talonId){
		$this->insertTurnCard($playerId, $talonId, false);
		$id = $this->db->insert_id();
		return $this->getTurnCardById($id);
		//updateTalonCardByGameId($talonId,$data){
	}
	
	private function getTurnCardById($turnCardId){
		$this->db->where('id',$turnCardId);
		return $this->db->get('turns')->result();
	}
	
	public function insertDefendTurn($playerId, $talonId){
		$cards = $this->getActiveTurnCards();
		$lastCardInsertedId = $cards[count($cards)-1]->id;
		$this->insertTurnCard($playerId, $talonId, $lastCardInsertedId);
		$id = $this->db->insert_id();
		return $this->getTurnCardById($id);
	}
	
	private function insertTurnCard($playerId, $talonId, $turnId){
		$insertData = array(	
							"talon_id"=>$talonId,
							"player_id"=>$playerId,
							"active"=>true,
							"status"=> ($turnId!=false) ? "I defended" : "I attack",
							"turn_id"=> ($turnId!=false) ? $turnId : 0
							);
		$this->db->insert('turns',$insertData);
	}
}
?>